package com.translator.engine.ai;

import com.translator.config.AppConfig;
import com.translator.engine.TranslationEngine;
import com.translator.model.Language;
import com.translator.model.TranslationRequest;
import com.translator.model.TranslationResult;

/**
 * AI翻译引擎抽象基类
 * 为所有AI翻译引擎提供共同的基础实现
 */
public abstract class AbstractAITranslationEngine implements TranslationEngine {
    
    protected String apiKey;
    protected String engineName;
    
    /**
     * 构造函数
     * 
     * @param engineName 引擎名称
     */
    public AbstractAITranslationEngine(String engineName) {
        this.engineName = engineName;
        this.apiKey = AppConfig.getInstance().getApiKey(engineName);
    }
    
    @Override
    public String getEngineName() {
        return engineName;
    }
    
    @Override
    public boolean requiresApiKey() {
        return true;
    }
    
    @Override
    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }
    
    @Override
    public boolean isConfigValid() {
        return apiKey != null && !apiKey.isEmpty();
    }
    
    @Override
    public TranslationResult translate(TranslationRequest request) throws Exception {
        // 确保代理设置已应用
        com.translator.util.ProxyManager.getInstance().applyProxySettings();
        
        if (!isConfigValid()) {
            throw new Exception("API密钥未配置，请在设置中配置" + engineName + "的API密钥");
        }
        
        long startTime = System.currentTimeMillis();
        
        // 获取语言代码
        String sourceLanguageCode = Language.getCodeByName(request.getSourceLanguage());
        String targetLanguageCode = Language.getCodeByName(request.getTargetLanguage());
        
        if (sourceLanguageCode == null || targetLanguageCode == null) {
            throw new Exception("不支持的语言");
        }
        
        // 执行翻译
        String translatedText = doTranslate(request.getSourceText(), sourceLanguageCode, targetLanguageCode);
        
        long endTime = System.currentTimeMillis();
        
        // 创建翻译结果
        return new TranslationResult(
                translatedText,
                request.getSourceLanguage(),
                request.getTargetLanguage(),
                engineName,
                endTime - startTime
        );
    }
    
    /**
     * 执行具体的翻译操作，由子类实现
     * 
     * @param sourceText 源文本
     * @param sourceLanguageCode 源语言代码
     * @param targetLanguageCode 目标语言代码
     * @return 翻译后的文本
     * @throws Exception 如果翻译过程中发生错误
     */
    protected abstract String doTranslate(String sourceText, String sourceLanguageCode, String targetLanguageCode) throws Exception;
}